package com.lanchetech.service.impl;


import com.lanchetech.common.enums.*;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.CommonFarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Service
public class CommonFarmServiceImpl implements CommonFarmService {

    @Autowired
    UserTaskMapper userTaskMapper;

    @Autowired
    UserRelationshipMapper userRelationshipMapper;

    @Autowired
    FarmTaskMapper farmTaskMapper;

    @Autowired
    GrassFlowMapper grassFlowMapper;

    @Autowired
    WaterFlowMapper waterFlowMapper;

    @Autowired
    FarmUserMapper farmUserMapper;

    private Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    private Date getEndTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 23);
        todayStart.set(Calendar.MINUTE, 59);
        todayStart.set(Calendar.SECOND, 59);
        todayStart.set(Calendar.MILLISECOND, 59);
        return todayStart.getTime();
    }

    @Override
    public boolean checkTaskDone(User user, Long kind, Long relateId, Long count) {
        // 先判断今天是否有领取任务，如果有多个同类型的任务，则先领取的先做；如果不满足，再切换到下一个；

        Date todayStart = getStartTime();
        Date todayEnd = getEndTime();

        List<UserTask> userTaskList = userTaskMapper.findAllByUserIdAndKindAndTaskTimeAndStatus(user.getId(), kind, todayStart, ToggleEnum.OFF.getStatus());

        if (!userTaskList.isEmpty()) {

            // 逐个判断是否已达成任务
            boolean done = false;
            for (UserTask item : userTaskList) {
                // 如果已经完成，则跳出循环
                if (done) break;

                FarmTask farmTask = farmTaskMapper.selectByPrimaryKey(item.getTaskId());

                if (ToggleEnum.ON.getStatus().equals(farmTask.getStatus())) {
                    switch (FarmTaskKindEnum.getByKind(kind)) {
                        case INVITE:
                            Long result = userRelationshipMapper.countBySuperiorIdAndTime(user.getId(), todayStart, todayEnd);
                            if (result != null && result >= farmTask.getCount()) {
                                done = true;
                                doneTask(item, farmTask);
                            }
                            break;
                        case ALL_FREE_SPU:
                            done = true;
                            doneTask(item, farmTask);
                            break;
                        case TARGET_FREE_SPU:
                            if (farmTask.getRelateId().equals(relateId) && count >= farmTask.getCount()) {
                                done = true;
                                doneTask(item, farmTask);
                            }
                            break;
                        case ALL_SHOP_SPU:
                            done = true;
                            doneTask(item, farmTask);
                            break;
                        case TARGET_SHOP_SPU:
                            if (farmTask.getRelateId().equals(relateId) && count >= farmTask.getCount()) {
                                done = true;
                                doneTask(item, farmTask);
                            }
                            break;
                        case SIGN_IN:
                            done = true;
                            doneTask(item, farmTask);
                            break;
                        case SIGN_IN_CUMULATIVE:
                            if(count >= farmTask.getCount()){
                                done = true;
                                doneTask(item, farmTask);
                            }
                            break;
                        case VIEW_URL:
                            if (farmTask.getId().equals(relateId)) {
                                done = true;
                                doneTask(item, farmTask);
                            }
                            break;
                        case POSTER:
                            done = true;
                            doneTask(item, farmTask);
                            break;
                        default:
                            break;
                    }
                }
            }
            return done;
        } else {
            return false;
        }
    }

    private void doneTask(UserTask userTask, FarmTask farmTask) {
        FarmUser farmUser = farmUserMapper.findOneByUserId(userTask.getUserId());

        userTask.setStatus(ToggleEnum.ON.getStatus());
        userTask.setUpdatedAt(new Date());
        userTaskMapper.updateByPrimaryKeySelective(userTask);

        // 奖励对应的草料
        if (FarmTypeEnum.COW.getType().equals(farmTask.getType())) {
            GrassFlow grassFlow = GrassFlow.builder()
                    .userId(userTask.getUserId())
                    .amount(farmUser.getGrass().add(farmTask.getReward()))
                    .tradeType(GrassFlowTradeType.TASK.getGrassFlowTradeType())
                    .type(GrassFlowTradeType.TASK.getType())
                    .weight(farmTask.getReward())
                    .remark(farmTask.getName())
                    .createdAt(new Date())
                    .build();
            grassFlowMapper.insert(grassFlow);

            farmUser.setGrass(farmUser.getGrass().add(farmTask.getReward()));
            farmUserMapper.updateByPrimaryKeySelective(farmUser);
        }

        // 奖励对应的水
        if (FarmTypeEnum.TREE.getType().equals(farmTask.getType())) {
            //水能量流水
            WaterFlow waterFlow = WaterFlow.builder()
                    .userId(userTask.getUserId())
                    .amount(farmUser.getWater().add(farmTask.getReward()))
                    .tradeType(WaterFlowTradeType.TASK.getWaterFlowTradeType())
                    .type(WaterFlowTradeType.TASK.getType())
                    .weight(farmTask.getReward())
                    .remark(farmTask.getName())
                    .createdAt(new Date())
                    .build();
            waterFlowMapper.insert(waterFlow);

            farmUser.setWater(farmUser.getWater().add(farmTask.getReward()));
            farmUserMapper.updateByPrimaryKeySelective(farmUser);
        }
    }
}